#!/usr/bin/env node

// const url = 'http://api.tianapi.com/txapi/xingzuo/index?key=1d89bae77797cf1c4469e459bc46e469&me='
// const args = process.argv[2];
// const axios = require('axios')
// axios.get(url+encodeURI(args)).then(res=>{
//     // console.log(res);
//     let str = '';
//     if(res.data.code==200){
//         let obj = res.data.newslist[0];
//         for(let k in obj ){
//             str+=`${k},${obj[k]}`
//         }
//         console.log(str);
//     }
// })

// console.log('anyserver');
const args = process.argv.slice(2);
let PORT = 8000;
const http = require("http");
const path = require("path");
const { existsSync, statSync, readdirSync, readFileSync } = require("fs");
const { networkInterfaces } = require("os");
const { exec } = require("child_process");

function fun() {
  http.fun((req, res) => {
    let rootpath = process.cwd();
    rootpath = path.join(rootpath, req.url);
    if (existsSync(rootpath)) {
      if (statSync(rootpath).isDirectory()) {
        let html = readFileSync(path.join(__dirname, "./index.html"));
        let dirarr = readdirSync(rootpath);
        let lihtml = dirarr
          .map((item) => {
            return `
                <li>
                <a href='${path.join(req.url, item)}'>${item}
                </li>
                `;
          })
          .join('');
          html = html.replace('{{list}}',lihtml)
          res.end(html)
      }else{
          res.end(readFileSync(rootpath),'utf-8')
      }
    }else{
        res.end('路径不在')
    }
  }).listen(PORT,()=>{

  })
}

if(args.length==0){
    console.log('端口号默认8000');
    fun()
}else{
    if(args[0]=='-v'){
        console.log('版本号1.0.0');
    }else if(args[0]=='-p'){
        console.log('端口号'+args[1]);
        PORT=args[1];
        fun()
    }
}
